{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pydicom,import shutilimport shutil\n",
    "from bmutils.pipelines import  AIEnginePredict\n",
    "import os\n",
    "archcta_case1_path = \"/deps/Biomind-Test-Data/data/NECK_CTA001\"\n",
    "archcta_case1_info = pydicom.read_file(os.path.join(archcta_case1_path, \"022bf07e-5de9c15f-2c0649c3-3d08bc0f-af4af5c9\"))\n",
    "\n",
    "# test case\n",
    "test_case_ARCHCTA = {\n",
    "    \"dcm_path\": archcta_case1_path,\n",
    "    \"study_uid\": archcta_case1_info.StudyInstanceUID,\n",
    "    \"protocols\": {\n",
    "        'pseries_classifier': {\n",
    "            'ARCHCTA': archcta_case1_info.SeriesInstanceUID,\n",
    "        },\n",
    "        'penable_cached_results': False\n",
    "    }\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "test_case_ARCHCTA"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from bmutils.insighttoolkit.utils import npy_to_png_str\n",
    "from bmutils.series import generate_series_dicom\n",
    "from bmutils.diseases import Diseases\n",
    "from bmutils.pipelines import Pipeline, Transform, AIEnginePredict, AIEngineTemplateToReport, \\\n",
    "    ProtocolValidator, TemplateToReportValidator, AnnotationValidator, \\\n",
    "    GenerateTestImage, AnyToNumpy"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "MRP_folder = '/Resources//MRP/'\n",
    "CTP_folder = \"/Resources/Biomind_CTP_01_/\"\n",
    "# test case\n",
    "test_case_CTP = {\n",
    "   # \"dcm_path\":CTP_folder,\n",
    "    \"study_uid\":\"1.2.840.113619.2.416.178512055267144187936510628798835029006\",\n",
    "    \"protocols\": {\n",
    "        'pseries_classifier': {\n",
    "             \"CTP\":\"1.2.840.113619.2.416.263797347391843930758744724964937820965\"\n",
    "        },\n",
    "        'penable_cached_results': False\n",
    "    }\n",
    "}\n",
    "test_case_MRP  = {\n",
    "    \"dcm_path\":MRP_folder,\n",
    "    \"study_uid\":'1.3.12.2.1107.5.2.32.35036.30000015052205525354600000139',\n",
    "    \"protocols\": {\n",
    "        'pseries_classifier': {\n",
    "             \"MRP\":'1.3.12.2.1107.5.2.32.35036.201505230148037020010505.0.0.0'\n",
    "        },\n",
    "        'penable_cached_results': False\n",
    "    }\n",
    "}\n",
    "cta_case1_path =  \"/deps/Biomind-Test-Data/data/CTA/\"\n",
    "cta_case1_info = pydicom.read_file(os.path.join(cta_case1_path, \"100_101.dcm\"))\n",
    "\n",
    "# test case\n",
    "test_case_CTA = {\n",
    "    \"dcm_path\": cta_case1_path,\n",
    "    \"study_uid\": cta_case1_info.StudyInstanceUID,\n",
    "    \"protocols\": {\n",
    "        'pseries_classifier': {\n",
    "            'CTA': \"1.2.840.113619.2.416.107808805190149939346544716073944641486\",\n",
    "        },\n",
    "        'penable_cached_results': False\n",
    "    }\n",
    "    \n",
    "} if test_case == None else test_case\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "test_case_ARCHCTA"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "output = AIEnginePredict(host=\"https://192.168.2.44\")([test_case_ARCHCTA[\"study_uid\"],test_case_ARCHCTA[\"protocols\"]])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "output.keys()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pickle\n",
    "with open(\"/Resources/output_ARCHCTA.pkl\", \"wb\") as fn:\n",
    "    pickle.dump(output, fn)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pickle\n",
    "with open(\"/Resources/output_ARCHCTA.pkl\", \"rb\") as fn:\n",
    "    payload = pickle.load(fn)\n",
    "payload.keys()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from bmutils.pipelines import  AnnotationValidator\n",
    "def test_additional(test_case, payload):\n",
    "    assert test_case[\"study_uid\"] == payload['pstudy_uid']\n",
    "    return True\n",
    "\n",
    "aiengine = AIEnginePredict(host=\"https://192.168.2.44\")\n",
    "payload = Pipeline.pipe(\n",
    "    aiengine,\n",
    "    # validate protocols\n",
    "    ProtocolValidator()\n",
    ").split(\n",
    "    # validate model specific tests\n",
    "    Transform(lambda x: test_additional(test_case_ARCHCTA, x))\n",
    ")([test_case_ARCHCTA[\"study_uid\"], test_case_ARCHCTA[\"protocols\"]])\n",
    "series = generate_series_dicom(test_case_ARCHCTA['dcm_path'])\n",
    "series_uid = list(payload[\"pprediction\"].keys())\n",
    "mask = payload[\"pprediction\"][series_uid[0]][0]['mask']\n",
    "# create dummy anotation\n",
    "annotation = {\n",
    "    'pannotation': {\n",
    "        archcta_case1_info.SeriesInstanceUID: {\n",
    "            Diseases.stenosis.key: {\n",
    "                'type': 'SegmentationMasksNpy',\n",
    "                'annotation': [mask]\n",
    "            }\n",
    "        }\n",
    "    }\n",
    "}   \n",
    "\n",
    "# validate annotation\n",
    "if os.environ.get('TEST_ANNOTATION_OFF', False):\n",
    "    log.debug(\"TEST_ANNOTATION_OFF enabled, skipping test\")\n",
    "else:\n",
    "    # validate annotation\n",
    "    AnnotationValidator(aiengine, series)([\n",
    "        test_case_ARCHCTA[\"study_uid\"],\n",
    "        { **test_case_ARCHCTA[\"protocols\"], **annotation}\n",
    "    ])\n",
    "    pass"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "payload"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### test CTA  predictor"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from bmutils.pipelines import  AnnotationValidator\n",
    "def test_additional(test_case, payload):\n",
    "    assert test_case[\"study_uid\"] == payload['pstudy_uid']\n",
    "    return payload\n",
    "\n",
    "cta_case1_path =  \"/deps/Biomind-Test-Data/data/CTA/\"\n",
    "cta_case1_info = pydicom.read_file(os.path.join(cta_case1_path, \"100_101.dcm\"))\n",
    "\n",
    "# test case\n",
    "test_case_CTA = {\n",
    "    \"dcm_path\": cta_case1_path,\n",
    "    \"study_uid\": cta_case1_info.StudyInstanceUID,\n",
    "    \"protocols\": {\n",
    "        'pseries_classifier': {\n",
    "            'CTA': \"1.2.840.113619.2.416.107808805190149939346544716073944641486\",\n",
    "        },\n",
    "        'penable_cached_results': False\n",
    "    }\n",
    "    }\n",
    "aiengine = AIEnginePredict(host=\"https://192.168.2.44\")\n",
    "payload = Pipeline.pipe(\n",
    "    aiengine,\n",
    "    # validate protocols\n",
    "    ProtocolValidator()\n",
    ").split(\n",
    "    # validate model specific tests\n",
    "    Transform(lambda x: test_additional(test_case_CTA, x))\n",
    ")([test_case_CTA[\"study_uid\"], test_case_CTA[\"protocols\"]])\n",
    "\n",
    "series = generate_series_dicom(test_case_CTA['dcm_path'])\n",
    "series_uid = list(payload[0][\"pprediction\"].keys())\n",
    "mask = payload[0][\"pprediction\"][series_uid[0]][0]['mask']\n",
    "# create dummy anotation\n",
    "annotation = {\n",
    "        'pannotation': {\n",
    "            cta_case1_info.SeriesInstanceUID: {\n",
    "                Diseases.stenosis.key: {\n",
    "                    'type': 'SegmentationMasksNpy',\n",
    "                    'annotation': [mask]\n",
    "                }\n",
    "            }\n",
    "        }\n",
    "    }   \n",
    "\n",
    "# validate annotation\n",
    "if os.environ.get('TEST_ANNOTATION_OFF', False):\n",
    "    log.debug(\"TEST_ANNOTATION_OFF enabled, skipping test\")\n",
    "else:\n",
    "    # validate annotation\n",
    "    AnnotationValidator(aiengine, series)([\n",
    "        test_case_CTA[\"study_uid\"],\n",
    "        { **test_case_CTA[\"protocols\"], **annotation}\n",
    "    ])\n",
    "    pass"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## test corocta predictor"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from bmutils.pipelines import  AnnotationValidator\n",
    "def test_additional(test_case, payload):\n",
    "    assert test_case[\"study_uid\"] == payload['pstudy_uid']\n",
    "    return payload\n",
    "\n",
    "corocta_case1_path = \"/deps/Biomind-Test-Data/data/CTA/\"\n",
    "corocta_case1_info = pydicom.read_file(os.path.join(corocta_case1_path, \"100_101.dcm\"))\n",
    "\n",
    "# test case\n",
    "test_case_corocta = {\n",
    "    \"dcm_path\": corocta_case1_path,\n",
    "    \"study_uid\": corocta_case1_info.StudyInstanceUID,\n",
    "    \"protocols\": {\n",
    "        'pseries_classifier': {\n",
    "            'COROCTA': corocta_case1_info.SeriesInstanceUID,\n",
    "        },\n",
    "        'penable_cached_results': False\n",
    "    }\n",
    "}\n",
    "aiengine = AIEnginePredict(host=\"https://192.168.2.44\")\n",
    "payload = Pipeline.pipe(\n",
    "    aiengine,\n",
    "    # validate protocols\n",
    "    ProtocolValidator()\n",
    ").split(\n",
    "    # validate model specific tests\n",
    "    Transform(lambda x: test_additional(test_case_corocta, x))\n",
    ")([test_case_corocta[\"study_uid\"], test_case_corocta[\"protocols\"]])\n",
    "\n",
    "series = generate_series_dicom(test_case_corocta['dcm_path'])\n",
    "series_uid = list(payload[0][\"pprediction\"].keys())\n",
    "mask = payload[0][\"pprediction\"][series_uid[0]][0]['mask']\n",
    "# create dummy anotation\n",
    "annotation = {\n",
    "        'pannotation': {\n",
    "            corocta_case1_info.SeriesInstanceUID: {\n",
    "                Diseases.stenosis.key: {\n",
    "                    'type': 'SegmentationMasksNpy',\n",
    "                    'annotation': [mask]\n",
    "                }\n",
    "            }\n",
    "        }\n",
    "    }   \n",
    "\n",
    "# validate annotation\n",
    "if os.environ.get('TEST_ANNOTATION_OFF', False):\n",
    "    log.debug(\"TEST_ANNOTATION_OFF enabled, skipping test\")\n",
    "else:\n",
    "    # validate annotation\n",
    "    AnnotationValidator(aiengine, series)([\n",
    "        test_case_corocta[\"study_uid\"],\n",
    "        { **test_case_corocta[\"protocols\"], **annotation}\n",
    "    ])\n",
    "    pass"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pickle\n",
    "with open(\"/Resources/output_COROCTA.pkl\", \"wb\") as fn:\n",
    "    pickle.dump(payload, fn)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open(\"/Resources/output_COROCTA.pkl\", \"rb\") as fn:\n",
    "    payload = pickle.load(fn)\n",
    "payload[0].keys()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "payload[0][\"pprediction\"]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "test_case = {\n",
    "    \"study_uid\": '1.2.840.113619.2.416.266453326091684583138340293391469751478',\n",
    "    \"protocols\": {\n",
    "        'pseries_classifier': {\n",
    "            'CTP': \"1.2.840.113619.2.416.49774313636150220478330468144746817761\",\n",
    "        },\n",
    "        'penable_cached_results': False\n",
    "    }\n",
    "}\n",
    "test_case_MRP  = {\n",
    "    \"study_uid\":'1.3.12.2.1107.5.2.32.35036.30000015052205525354600000139',\n",
    "    \"protocols\": {\n",
    "        'pseries_classifier': {\n",
    "             \"MRP\":\"1.3.12.2.1107.5.2.32.35036.201505230148037020010505.0.0.0\"\n",
    "        },\n",
    "        'penable_cached_results': False\n",
    "    }\n",
    "} if test_case == None else test_case\n",
    "# additional tests\n",
    "def test_additional(test_case, payload):\n",
    "    assert test_case[\"study_uid\"] == payload['pstudy_uid']\n",
    "    return True\n",
    "\n",
    "aiengine = AIEnginePredict(host=\"https://192.168.2.44\")\n",
    "Pipeline.pipe(\n",
    "    aiengine,\n",
    "    # validate protocols\n",
    "    ProtocolValidator()\n",
    ").split(\n",
    "    # validate model specific tests\n",
    "    Transform(lambda x: test_additional(test_case_MRP, x))\n",
    ")([test_case_MRP[\"study_uid\"], test_case_MRP[\"protocols\"]])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.10"
  },
  "widgets": {
   "application/vnd.jupyter.widget-state+json": {
    "state": {},
    "version_major": 2,
    "version_minor": 0
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
